﻿/*
   Copyright 2012 University of Southampton

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uk.ac.soton.ses.DAL;
using System.Web;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;
using System.Web.UI;

namespace uk.ac.soton.ses
{
    public static class HttpContextExtensions
    {
        /// <summary>
        /// Return the shared configuration options object, creating it if required. This is shared across the HttpContext.
        /// </summary>
        /// <param name="httpContext">The HttpContext</param>
        /// <returns>The configuration options</returns>
        public static HDCConfigurationOptions GetHDCConfigurationOptions(this HttpContext httpContext)
        {
            string cfgkey = "HDCConfigurationOptions" + httpContext.GetHashCode().ToString("x");
            object configObject = httpContext.Items[cfgkey];
            if (configObject == null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    configObject = HDCConfiguration.GetConfigurationOptions();
                    httpContext.Items.Add(cfgkey, configObject);
                });
            }
            return configObject as HDCConfigurationOptions;
        }

        /// <summary>
        /// Return the shared database context, creating one if required.
        /// This is shared across the HttpContext. When using this, ensure it is disposed of correctly, perhaps after the web page has finished creating
        /// </summary>
        /// <param name="httpContext">The HttpContext</param>
        /// <returns>The database context</returns>
        public static MaterialsMetadataContext GetMaterialsDBContext (this HttpContext httpContext)
        {
            string ctxkey = "MaterialsDBContext" + httpContext.GetHashCode().ToString("x"); //int.ToString("x") means to hexadecimal
            object contextObject = httpContext.Items[ctxkey];
            if (contextObject == null)
            {
                //Load the configuration settings to retrieve the connection string
                HDCConfigurationOptions hdcConfig = httpContext.GetHDCConfigurationOptions();
                string hdcConnectionString = hdcConfig.DatabaseOptions.EntityConnectionString;

                //We need to create the connection to the database as the application pool user who has read and write permissions to the database
                //Any other users do not have permission to the database as they could bypass the API that checks the users rights to Experiments
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    //Create and open the connection ourselves to ensure it gets created with the correct permissions
                    System.Data.EntityClient.EntityConnection conn = new System.Data.EntityClient.EntityConnection(HDCConfiguration.GetConfigurationOptions().DatabaseOptions.EntityConnectionString);
                    conn.Open();

                    //Pass the connection to the db context
                    contextObject = new MaterialsMetadataContext(conn);
                    httpContext.Items.Add(ctxkey, contextObject);
                });
            }

            return contextObject as MaterialsMetadataContext;
        }

        public static HtmlLink AddHDCStylesheet(this Page parentPage)
        {
            string ctxkey="hdc.css"+parentPage.GetHashCode().ToString("x");
            object ctxObject = parentPage.Items[ctxkey];
            if (ctxObject == null)
            {
                HtmlLink cssLink = new HtmlLink();
                cssLink.Attributes["rel"] = "stylesheet";
                cssLink.Attributes["type"] = "text/css";

                //We don't want to have the CSS cached so we append the date to the URL
                cssLink.Href = "/_layouts/HDC/CSS/hdc.css?date=" + DateTime.Now.ToString("ddMMyyHH");
                parentPage.Items.Add(ctxkey, cssLink);
                parentPage.Header.Controls.Add(cssLink);
                return cssLink;
            }
            else
            {
                return ctxObject as HtmlLink;
            }
        }

        public static void AddHDCJQuery(this Page parentPage, bool addUI)
        {
            string ctxkey = "jquery" + parentPage.GetHashCode().ToString("x");
            string ctxkeyui = "ui" + ctxkey;
            object ctxObjectUI = parentPage.Items[ctxkeyui];

            //Add JQuery CSS to page header
            if (addUI && ctxObjectUI == null)
            {
                HtmlLink cssLink = new HtmlLink();
                cssLink.Attributes["rel"] = "stylesheet";
                cssLink.Attributes["type"] = "text/css";
                cssLink.Href = "/_layouts/HDC/CSS/jquery-ui-1.8.24/jquery-ui.min.css";
                parentPage.Items.Add(ctxkeyui, cssLink);
                parentPage.Header.Controls.Add(cssLink);
            }

            //Add JQuery script
            if (!parentPage.ClientScript.IsClientScriptIncludeRegistered(ctxkey))
            {
                parentPage.ClientScript.RegisterClientScriptInclude(ctxkey, "/_layouts/HDC/Scripts/jquery-1.4.4.min.js");
            }

            //Add JQuery UI
            if (addUI && !parentPage.ClientScript.IsClientScriptIncludeRegistered(ctxkeyui))
            {
                parentPage.ClientScript.RegisterClientScriptInclude(ctxkeyui, "/_layouts/HDC/Scripts/jquery-ui-1.8.24/jquery-ui.min.js");
            }
        }

        public static void AddHDCJavaScript(this Page parentPage)
        {
            string ctxkey = "hdcjscript" + parentPage.GetHashCode().ToString("x");
            object ctxObject = parentPage.Items[ctxkey];

            //Add HDC JavaScript
            if (!parentPage.ClientScript.IsClientScriptIncludeRegistered(ctxkey))
            {
                //We don't want to have the CSS cached so we append the date to the URL
                parentPage.ClientScript.RegisterClientScriptInclude(ctxkey, "/_layouts/HDC/Scripts/hdc.js?date=" + DateTime.Now.ToString("ddMMyyHH"));
            }
        }
    }
}
